package com.hxstrive.freemarker.demo1;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.*;

public class Demo4 {

    public static void main(String[] args) throws Exception {
        // 1. 配置 FreeMarker
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        cfg.setClassForTemplateLoading(Demo4.class, "/templates/");
        cfg.setDefaultEncoding("UTF-8");
        cfg.setLocale(Locale.CHINESE);
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        // 2. 准备模版数据
        Map<String, Object> input = new HashMap<String, Object>();
        List<Map<String,Object>> bookList = new ArrayList<Map<String,Object>>();
        input.put("books", bookList);
        input.put("title", "编程书籍推荐");

        Map<String,Object> javaBook = new HashMap<String, Object>();
        javaBook.put("name", "Java高级编程");
        javaBook.put("price", 67.5f);
        bookList.add(javaBook);

        Map<String,Object> linuxBook = new HashMap<String, Object>();
        linuxBook.put("name", "Linux入门到精通");
        linuxBook.put("price", 36.8f);
        bookList.add(linuxBook);

        Map<String,Object> cssBook = new HashMap<String, Object>();
        cssBook.put("name", "CSS的艺术");
        cssBook.put("price", 44.5f);
        bookList.add(cssBook);

        Template template = cfg.getTemplate("template4.ftl");
        Writer consoleWriter = new OutputStreamWriter(System.out);
        template.process(input, consoleWriter);

        // 将输出结果保存到文件中
        Writer fileWriter = new FileWriter(new File("output.html"));
        try {
            template.process(input, fileWriter);
        } finally {
            fileWriter.close();
        }
    }

}
